Ext.namespace('ZZExt.widgets');

/**
 * 主键TextField code by zz
 * 
 * @class Wtp.widgets.KeyTextField
 * @extends Ext.form.TextField
 */
ZZExt.widgets.KeyTextField = Ext.extend(Ext.form.TextField, {
	url : 'key!validateKey.action',// 验证地址
	fieldLabel : '主键ID',
	validKeyStatus : -1,// 0:发送请求,1,验证成功,2失败,
	constructor : function(config) {
		Ext.apply(this, config);
		var continueKeyUp = true;
		ZZExt.widgets.KeyTextField.superclass.constructor.call(this, {
			enableKeyEvents : true,
			listeners : {
				'change' : function(field, newV, oldV) {
					this.validKeyStatus = -1;
					if (field.isValid()
							&& this.validateKeyInterceptor(field, newV, oldV)) {
						this.validateKey(newV);
					} else if (!this.validateKeyInterceptor(field, newV, oldV)) {// 如果是原始值,则将提示信息去掉,变为成功验证状态,提供回调函数
						this.clearInvalid();
						this.validKeyStatus = 1;
						this.initValueFn();
					}
				}
			}
		});
	},// constructor end,
	validateKeyInterceptor : function(f, newV, oldV) {
		if (this.initValue == newV)
			return false;
		return true;
	},
	validateKey : function(val) {
		this.validKeyStatus = 0;
		this.clearInvalid();
		var jsonString = '{"' + this.name + '":"' + val + '"}';
		var jsonData = Ext.decode(jsonString);
		Ext.Ajax.request({
			url : this.url,
			params : jsonData,
			method : 'POST',
			scope : this,
			success : function(response, opts) {
				this.successHandler(response, opts, val, this.errorMsg);
			},
			failure : function(response, opts) {
				this.msg = null;
				Ext.Msg.alert('系统提示', '无法完成验证:' + response.status);
			}

		});
	},

	successHandler : function(response, opts, val, errorMsg) {
		var obj = Ext.decode(response.responseText);
		if (obj.rows && obj.rows.length > 0) {
			this.markInvalid('关键字(' + val + ')已存在，请更换!');
			this.validKeyStatus = 2;
		} else {
			this.clearInvalid();
			this.validKeyStatus = 1;
			if (obj.additionalData) {
				this.additionalFn(obj.additionalData);
			} else if (!obj.additionalData && errorMsg != null) {
				this.markInvalid(errorMsg);
				this.validKeyStatus = 2;
			}
		}

	},
	// 空格验证
	validator : function(text) {
		var n = Ext.util.Format.trim(text);
		if (this.allowBlank == false && n.length != text.length)
			return '不允许以空格开始或结束！';
		else {
			if (this.validKeyStatus == 2) {
				return '关键字(' + text + ')已存在';
			} else if (this.validKeyStatus == 0) {
				return '正在验证是否存在...';
			}
		}
		return true;
	}
});
Ext.reg('keytextfield', ZZExt.widgets.KeyTextField);